define(['jquery', 'bootstrap-datetimepicker.min'], function($) {

var commData = {
	pageNum: Math.round($(window).height() / 170),// 一页显示多少条数据
	curPage: 0,// 当前页码
	departments: [],
	adminPrivs: [],
	users: [],
	categorys: [],
	softs: [],
	userActiveSofts: [],
	userLicenseReqs: [],
	userLicenses: [],
	deptLicenses: [],
	domKey: {
	}
}

// 各模型的加载数据
var dataOpt = {
	adminOpt: {
		url: "/servlet/admin/QueryAdminPrivsServlet",
		data: {},
		name: "adminPrivs"
	},
	departmentOpt: {
		url: "/servlet/dept/QueryAllDeptServlet",
		data: {},
		name: "departments"
	},
	privNameOpt: {
		url: "/servlet/QueryAllPrivNameServlet",
		data: {},
		name: "privNames"
	},
	userOpt: {
		url: "/servlet/user/QueryAllUsersServlet",
		data: {},
		name: "users"
	},
	categoryOpt: {
		url: "/servlet/QueryAllCategorysServlet",
		data: {},
		name: "categorys"
	},
	softwareOpt: {
		url: "/servlet/soft/QuerySoftsServlet",
		data: {},
		name: "softs"
	},
	deptLicenseOpt: {
		url: "/servlet/dept/QueryDeptLicenseServlet",
		data: {},
		name: "deptLicenses"
	},
	userActiveSoftOpt: {
		url: "/servlet/user/QueryUserActiveSoftServlet",
		data: {},
		name: "userActiveSofts"
	},
	userLicenseReqOpt: {
		url: "/servlet/user/QueryUserLicenseReqServlet",
		data: {},
		name: "userLicenseReqs"
	},
	userLicenseOpt: {
		url: "/servlet/user/QueryUserLicenseServlet",
		data: {},
		name: "userLicenses"
	},
	downloadOpt: {
		url: "/servlet/soft/QueryDownloadsServlet",
		data: {},
		name: "downloads"
	},
	recordAmountOpt: {
		url: "/servlet/user/QueryRecordAmountServlet",
		data: {},
		name: "recordAmounts"
	},
	errCodeOpt: {
		url: "/servlet/QueryErrCodeServlet",
		data: {},
		name: "errCodes"
	}
}

var initData = function(args) {
	$.extend(true, commData, args);
}

//清空模态框及其按钮点击事件、释放按钮
var cleanModal = function() {
	commData.domKey.modal.find(".modal-dialog").removeClass("modal-sm").removeClass("modal-lg");
	commData.domKey.modalLabel.html("----");
	commData.domKey.modalBody.html("----");
	commData.domKey.modalAct.html("----").show().off("click");
	enable(commData.domKey.modalAct);
}

//点击提交表单
var clickSubmit = function (form) {
	$(form).submit();
};

// 禁用按钮
var disable = function (btn) {
    btn.attr({"disabled":true});
    return true;
}

// 打开按钮
var enable = function(btn) {
	btn.attr({"disabled":false});
    return true;
}

// 全选、不全选（权限分配）
var checkedChange = function(id) {
	$("#" + id).on("change", function() {
	    var isChecked = $(this).prop("checked");
	    $(":checkbox[id^='" + id + "-priv-']").each(function() {
	    	$(this).prop("checked", isChecked).change();
	    });
	});
}

// 状态switch
var switchStatusAjax = function(table, status, name) {
	var data = {
		"table": table,
		"status": status,
		"name": name
	};
	$.ajax({
		url: commData.contextPath + "/servlet/SwitchStatusServlet",
		type: "post",
		data: data,
		dataType: "json",
		async: false,
		success: function(data) {
			if("1" == data["retCode"]) {
				//
			} else {
				alert(data["desc"] + ":SwitchStatusServlet");
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("SwitchStatusServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
		},
		complete: function() {
			// _initSoftTables();
		}
	});
}

// 绑定下拉菜单跳转页面
var menusBind = function(opt) {
	opt.menuDom.click(function() {
		commData.domKey.content.load(commData.contextPath + opt.url);
		commData.curPage = 0;
		$("#page_nav").addClass("hidden").parent().removeClass("hidden");
	});
}

// 使用一个ajax加载数据模板
var ajaxLoadData = function(opt) {
	var returnData = [];
	$.ajax({
		url: commData.contextPath + opt.url,
		type: "get",
		data: opt.data,
		dataType: "json",
		async: false,
		success: function(data) {
			data = eval(data);
			if("1" == data["retCode"]) {
				returnData = data[opt.name];
				// console.log(opt.name + ": " + returnData);
			} else {
				returnData = [];
				// alert(data["desc"] + opt.name);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			returnData = [];
			alert(opt.url + ":" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
		},
		complete: function() {

		}
	});
	return returnData;
}

// 审批用户
var approveUser = function(userName) {
	$.ajax({
		url: commData.contextPath + "/servlet/user/EditUserStatusServlet",
		type: "post",
		data: {"userName":userName},
		dataType: "json",
		async: false,
		success: function(data) {
			if("1" == data["retCode"]) {
				
			} else {
				alert(data["desc"]);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("common-approveUser:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
		}
	});
}

// 清除session
var cleanSession = function(data) {
	$.ajax({
		url: commData.contextPath + "/servlet/CleanSessionServlet",
		type: "post",
		data: data,
		dataType: "json",
		async: false,
		success: function(json) {

		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("CleanSessionServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
		},
		complete: function() {
			window.location.reload();
		}
	});
}

// 修改密码
var editPassword = function(opt) {
	$.ajax({
		url: commData.contextPath + "/servlet/EditPasswordServlet",
		type: "post",
		data: opt.data,
		dataType: "json",
		async: false,
		success: function(json) {
			if("1" == json["retCode"]) {
				opt.fun();
			} else {
				alert(json["desc"]);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("EditPasswordServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
		},
		complete: function() {
			domKey.modal.find(".close").click();
		}
	});
}

// 到处数据统计的excel
var exportExcel = function(name) {
	$("#export_excel").click(function() {
		tableExport("t_excel", name, "xls");
	});
	
}

// 分页功能
var pageNav = function(opt, callback) {
	var htmlArr = opt.htmlArr;
	var totalPage = htmlArr.length;
	// var curPage = commData.curPage;
	
	// 大于一页才显示分页导航
	if(totalPage > 1) {
		$("#page_nav").removeClass("hidden");
	}

	// 分页导航
	var html = "<li id='prev_page'><a href='javascript:;'><span>&laquo;</span></a></li>";
	for(var i = 0; i < totalPage; i++) {
		var li = "<li data-page='" + i + "'><a href='javascript:;'>" + (i+1) + "</a></li>";
		html += li;
	}
	html += "<li id='next_page'><a href='javascript:;'><span>&raquo;</span></a></li>";

	var goPage = function() {
		// console.log(curPage);
		if(commData.curPage < 0) {
			commData.curPage = 0;
		} else if(commData.curPage > totalPage - 1) {
			commData.curPage = totalPage - 1;
		}
		opt.content.html(htmlArr[commData.curPage] ? htmlArr[commData.curPage]: "");
		$("#page_nav li:eq(" + (commData.curPage + 1) + ")").siblings().removeClass("active").end().addClass("active");
		if(callback && typeof callback == "function") {
			callback();
		};
	}

	// 页数选择
	$("#page_nav").html(html).on("click", "li:not(:first):not(:last)", function() {
		commData.curPage = $(this).data("page");
		goPage();
	});

	// 上一页
	$("#prev_page").click(function() {
		commData.curPage--;
		goPage();
	});

	// 下一页
	$("#next_page").click(function() {
		commData.curPage++;
		goPage();
	});

	goPage();
}

// 密码验证：数字，字母下划线
function isPasswd(s)
{
	var patrn=/^(\w){6,20}$/;
	if (!patrn.exec(s)) return false;
	return true;
}
function isName(s) {
    var patrn=/^(\w){1,20}$/;
    if (!patrn.exec(s)) return false;
    return true;
}

// 日期控件初始化
var datePickerInit = function(el) {
	// require(["bootstrap-datetimepicker.zh-CN"]);
	$(el).datetimepicker({
		format: 'yyyy-mm-dd',// 日期的格式
		autoclose: true,// 日期选择完成后是否关闭选择框
		bootcssVer: 3,// 显示向左向右的箭头
		language: 'zh_CN',// 语言
		minView: 2,// 表示日期选择的最小范围，默认是hour
		todayBtn: true,
		pickerPosition: "bottom-left",
		keyboardNavigation: false
	});
}

return {
	initData: initData,
	commData: commData,
	dataOpt: dataOpt,
	clickSubmit: clickSubmit,
	disable: disable,
	enable: enable,
	cleanModal: cleanModal,
	checkedChange: checkedChange,
	switchStatusAjax: switchStatusAjax,
	ajaxLoadData: ajaxLoadData,
	approveUser: approveUser,
	menusBind: menusBind,
	cleanSession: cleanSession,
	editPassword: editPassword,
	exportExcel: exportExcel,
	pageNav: pageNav,
	isPasswd: isPasswd,
	isName: isName,
	datePickerInit: datePickerInit
}
});